﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using Morphine.Base;
using Morphine.Media;
using WMPLib;
using Color = System.Windows.Media.Color;

namespace Morphine
{
    /// <summary>
    /// Interaction logic for MiniModeWindow.xaml
    /// </summary>
    public partial class MiniModeWindow : Window
    {
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateEllipticRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);

        [DllImport("user32.dll")]

        static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);

        public MiniModeWindow()
        {
            InitializeComponent();
        }

        private void WindowSourceInitialized(object sender, EventArgs e)
        {
            var handle = new WindowInteropHelper(this).Handle;

            var rgn = CreateEllipticRgn(10, 10, (int)this.Width-10, (int)this.Height-10);

            Dwm.MakeGlassRegion(ref handle, rgn);

            this.Left = App.Settings.Left;
            this.Top = App.Settings.Top;

            LocationChanged += WindowLocationChanged;

            App.MediaPlayer.MediaChange += MediaPlayerMediaChange;
            App.MediaPlayer.PlayStateChange += MediaPlayerPlayStateChange;

            if (App.MediaPlayer.currentPlaylist.count > 0)
            {
                MediaPlayerMediaChange(App.MediaPlayer.currentMedia);
            }

            if (App.MediaPlayer.playState == WMPPlayState.wmppsPlaying)
                PlayButton.IsChecked = true;

            if (App.Settings.TopMost)
                TopMostItem.IsChecked = true;
        }

        private void WindowMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
                DragMove();
        }

        private void WindowActivated(object sender, EventArgs e)
        {
            WindowShadowImage.Opacity = 1;
        }

        private void WindowDeactivated(object sender, EventArgs e)
        {
            WindowShadowImage.Opacity = 0.2;
        }


        private void WindowLocationChanged(object sender, EventArgs e)
        {
            App.Settings.Left = this.Left;
            App.Settings.Top = this.Top;
        }

        private void OpenItemClick(object sender, RoutedEventArgs e)
        {
            var openDialog = new OpenFileDialog();
            openDialog.Multiselect = true;
            if (openDialog.ShowDialog() == true)
            {
                App.MediaPlayer.currentPlaylist.clear();

                if (App.Settings.RecentItems == null)
                    App.Settings.RecentItems = new List<string>();
                var p = App.MediaPlayer.newPlaylist("Untitled", "");

                var tempPlaylist = new List<MediaInfo>();

                foreach (var name in openDialog.FileNames)
                {
                    var media = App.MediaPlayer.newMedia(name);
                    p.appendItem(media);
                    //App.MediaPlayer.currentPlaylist.appendItem(media);
                    var info = MediaInfo.GetInfo(media);
                    tempPlaylist.Add(info);
                }

                Playlist.Save(App.Path + "\\lastplaylist", tempPlaylist);

                App.MediaPlayer.currentPlaylist = p;
                App.MediaPlayer.controls.play();
                //Playlist.SelectedIndex = GetCurrentMediaIndex();

            }
        }

        void MediaPlayerMediaChange(object item)
        {
            if (item == null)
                return;

            PlayButton.IsEnabled = true;
            PrevButton.IsEnabled = true;
            NextButton.IsEnabled = true;

            var info = MediaInfo.GetInfo(App.MediaPlayer.currentMedia);
            if (MediaTitleTextBlock.Text == info.Title)
                return;
            MediaTitleTextBlock.Text = info.Title;
            ArtistNameTextBlock.Text = info.Artist;

            if (string.IsNullOrEmpty(info.Cover))
            {
                AlbumCover.Source = null;
                return;
            }
            if (AlbumCover.Source != null && ((BitmapImage)AlbumCover.Source).UriSource.LocalPath == info.Cover)
                return;

            AlbumCover.Source = new BitmapImage(new Uri(info.Cover));

            if (App.Settings.EnableDynamicColor)
            {
                var bmp = new Bitmap(info.Cover);
                var color = Utils.CalcAverageColor(bmp);
                PlayButton.Background = new SolidColorBrush(Color.FromRgb(color.R, color.G, color.B));
            }
        }


        void MediaPlayerPlayStateChange(int newState)
        {
            switch (newState)
            {
                case (int)WMPLib.WMPPlayState.wmppsPlaying:

                    PlayButton.IsChecked = true;
                    App.MediaProgressTimer.Start();
                    break;
                case (int)WMPLib.WMPPlayState.wmppsStopped:
                    PlayButton.IsChecked = false;
                    //TimeEstimatedTextBlock.Text = "00:00";
                    App.MediaProgressTimer.Stop();
                    break;
                default:
                    PlayButton.IsChecked = false;
                    App.MediaProgressTimer.Stop();
                    break;
            }
        }

        private void WindowClosed(object sender, EventArgs e)
        {
            LocationChanged -= WindowLocationChanged;

            App.MediaPlayer.MediaChange -= MediaPlayerMediaChange;
            App.MediaPlayer.PlayStateChange -= MediaPlayerPlayStateChange;
        }

        private void CloseItemClick(object sender, RoutedEventArgs e)
        {
            App.Settings.TopMost = TopMostItem.IsChecked;
            this.Close();
        }

        private void PlayButtonClick(object sender, RoutedEventArgs e)
        {
            if (App.MediaPlayer.playState == WMPPlayState.wmppsPlaying)
                App.MediaPlayer.controls.pause();
            else
                App.MediaPlayer.controls.play();
        }

        private void NextButtonClick(object sender, RoutedEventArgs e)
        {
            App.MediaPlayer.controls.next();
        }

        private void PrevButtonClick(object sender, RoutedEventArgs e)
        {
            App.MediaPlayer.controls.previous();
        }

        private void MainModeItemClick(object sender, RoutedEventArgs e)
        {
            var w = new MainWindow();
            w.Show();
            App.Settings.IsMinimode = false;
            this.Close();
        }
    }
}
